package FlowGram.Application.Parser.Utility;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import FlowGram.Application.Parser.Actions.FunctionInvocation;

/**
 * 
 * @author thackray
 *
 */
public class ClassFinder {

	public static Class[] findActions(){
		ArrayList<String> excludePackages = new ArrayList<String>();
		excludePackages.add("FlowGram.Application.Parser.Actions.Property");
		ArrayList<String> excludeClasses = new ArrayList<String>();
		excludeClasses.add("FinchAction");
		excludeClasses.add("ControlAction");
		excludeClasses.add("FunctionInvocation");
		
		Class[] actions = null;
		try{
			actions = getClasses("FlowGram.Application.Parser.Actions");
			//actions = getClasses("Parser.Actions.Control");
		}catch(Exception e){
			
		}
		ArrayList<Class> finalClasses = new ArrayList<Class>();
		if(actions.length > 0){
			actionsLoop: for(int i=0; i<actions.length; i++){
				if(hasSuperClass(actions[i], "FinchAction")){
					for(int j=0; j<excludePackages.size(); j++){
						if(isContainedIn(actions[i], excludePackages.get(j))){
							continue actionsLoop;
						}
					}
					for(int j=0; j<excludeClasses.size(); j++){
						if(actions[i].getSimpleName().equals(excludeClasses.get(j))){
							continue actionsLoop;
						}
					}
					finalClasses.add(actions[i]);
				}
			}		
		}
		finalClasses.add(FunctionInvocation.class); // should be last
		actions = (Class[])finalClasses.toArray(new Class[finalClasses.size()]);
		return actions;
	}
	public static Class[] findProperties(){
		
		Class[] actions = null;
		try{
			actions = getClasses("FlowGram.Application.Parser.Actions.Property");
		}catch(Exception e){
			
		}
		ArrayList<Class> finalClasses = new ArrayList<Class>();
		if(actions.length > 0){
			for(int i=0; i<actions.length; i++){
				if(hasSuperClass(actions[i], "PropertyAction") && !actions[i].getSimpleName().equals("PropertyAction")){
					finalClasses.add(actions[i]);
				}
			}		
		}
		actions = (Class[])finalClasses.toArray(new Class[finalClasses.size()]);
		return actions;
	}
	
	private static boolean hasSuperClass(Class c, String name){
		while(!c.getSimpleName().equals("Object")){
			Class sup = c.getSuperclass();
			if(sup.getSimpleName().equals(name)){
				return true;
			}
			c = sup;
		}
		return false;
	}
	private static boolean isContainedIn(Class c, String pckg){
		if(c.getPackage().getName().equals(pckg)){
			return true;
		}
		return false;
	}
	/**
     * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
     *
     * @param packageName The base package
     * @return The classes
     * @throws ClassNotFoundException
     * @throws IOException
     */
    private static Class[] getClasses(String packageName)
            throws ClassNotFoundException, IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<File>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(URLDecoder.decode(resource.getFile(), "UTF-8")));
        }
        ArrayList<Class> classes = new ArrayList<Class>();
        for (File directory : dirs) {
            classes.addAll(findClasses(directory, packageName));
        }
        return classes.toArray(new Class[classes.size()]);
    }
    /**
     * Recursive method used to find all classes in a given directory and subdirs.
     *
     * @param directory   The base directory
     * @param packageName The package name for classes found inside the base directory
     * @return The classes
     * @throws ClassNotFoundException
     */
    private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
        List<Class> classes = new ArrayList<Class>();
        if (!directory.exists()) {
            return classes;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName()));
            } else if (file.getName().endsWith(".class")) {
                classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
            }
        }
        return classes;
    }
}
